package 面试v1.字节;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

public class Bm27 {

    //特殊的层次遍历
    public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
        if (pRoot == null) {
            return ret;
        }

        Deque<TreeNode> queue = new LinkedList<>();
        queue.add(pRoot);
        int level = 0;
        ArrayList<Integer> currentList = new ArrayList<Integer>();
        while (!queue.isEmpty()) {
            int size = queue.size();
            if (level % 2 == 0) {
                for (int i = 0; i < size; i++) {
                    TreeNode poll = queue.pollFirst();
                    currentList.add(poll.val);

                    if (poll.left != null) {
                        queue.offerLast(poll.left);
                    }

                    if (poll.right != null) {
                        queue.offerLast(poll.right);
                    }
                }
            } else {
                for (int i = 0; i < size; i++) {
                    TreeNode poll = queue.pollLast();
                    currentList.add(poll.val);

                    if (poll.right != null) {
                        queue.offerFirst(poll.right);
                    }

                    if (poll.left != null) {
                        queue.offerFirst(poll.left);
                    }
                }
            }
            level++;
            ret.add(currentList);
            currentList = new ArrayList<Integer>();
        }
        return ret;
    }
}
